package com.wzy.leecode.linked;

/**
 * @Auther: wzy
 * @Date: 2021/12/06/20:50
 * @Description:
 */
public class RevertLinkedByK {
    public static void main(String[] args) {
        Node head = new Node(1);
        for (int i = 2; i < 6; i++) {
            Node node = new Node(i);
            LinkedUtils.add(head,node);
        }
        LinkedUtils.print(head);

//        Node node = reverseKGroup(head, 3);
        Node node = LinkedUtils.reverse(head);
        System.out.println();
        LinkedUtils.print(node);

    }

    public static Node reverseKGroup(Node head, int k) {
        Node hair = new Node(0);
        hair.next = head;
        Node pre = hair;

        while (head != null) {
            Node tail = pre;
            // 查看剩余部分长度是否大于等于 k
            for (int i = 0; i < k; ++i) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            Node nex = tail.next;
            Node[] reverse = myReverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            // 把子链表重新接回原链表
            pre.next = head;
            tail.next = nex;
            pre = tail;
            head = tail.next;
        }

        return hair.next;
    }
    public static Node[] myReverse(Node head, Node tail) {
        Node prev = tail.next;
        Node p = head;
        while (prev != tail) {
            Node nex = p.next;
            p.next = prev;
            prev = p;
            p = nex;
        }
        return new Node[]{tail, head};
    }
}
